<template>
  <div class="p-6 bg-gray-100 min-h-screen">
    <h2 class="text-2xl font-bold mb-4">批量添加题目</h2>
    <div class="mb-4 flex items-center">
      <input ref="fileInput" type="file" accept=".xls,.xlsx" class="hidden" @change="onFileChange" />
      <button class="px-4 py-2 bg-blue-500 text-white rounded mr-4" @click="() => fileInput.click()">
        选择 Excel 文件
      </button>
      <input
        v-model="fileName"
        readonly
        placeholder="未选择文件"
        class="flex-1 border rounded p-2 bg-white"
      />
    </div>
    <el-button type="primary" :disabled="questions.length === 0" @click="previewDialog = true">
      预览题目
    </el-button>

    <el-dialog
      title="题目预览"
      v-model="previewDialog"
      width="80%"
    >
      <el-table :data="questions" stripe style="width: 100%">
        <el-table-column prop="content" label="题干" />
        <el-table-column prop="type" label="题型" width="80">
          <template #default="{ row }">
            {{ row.type === 0 ? '简答' : row.type === 1 ? '单选' : '判断' }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分值" width="80" />
        <el-table-column label="选项">
          <template #default="{ row }">
            <div v-if="row.type === 1 || row.type === 2">
              <div v-if="row.option1">A. {{ row.option1 }}</div>
              <div v-if="row.option2">B. {{ row.option2 }}</div>
              <div v-if="row.option3">C. {{ row.option3 }}</div>
              <div v-if="row.option4">D. {{ row.option4 }}</div>
            </div>
            <div v-else>—</div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onCancel">取消</el-button>
          <el-button type="primary" @click="onConfirm">确认上传</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import * as XLSX from 'xlsx'
import axios from 'axios'
import { ElButton, ElDialog, ElTable, ElTableColumn, ElMessage } from 'element-plus'

const fileInput = ref(null)
const fileName = ref('')
const questions = ref([])
const previewDialog = ref(false)

function onFileChange(e) {
  const file = e.target.files[0]
  if (!file) return
  fileName.value = file.name
  const reader = new FileReader()
  reader.onload = evt => {
    const data = new Uint8Array(evt.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const sheetName = workbook.SheetNames[0]
    const sheet = workbook.Sheets[sheetName]
    const raw = XLSX.utils.sheet_to_json(sheet, { header: 1 })
    const parsed = []
    for (let i = 1; i < raw.length; i++) {
      const row = raw[i]
      if (row && row[0]) {
        parsed.push({
          type: Number(row[0]),
          content: row[1] || '',
          score: Number(row[2] || 0),
          answer: row[3] || null,
          option1: row[4] || null,
          option2: row[5] || null,
          option3: row[6] || null,
          option4: row[7] || null,
          analysis: row[8] || null,
          subject: row[9] || null,
          file: row[10] || null,
        })
      }
    }
    questions.value = parsed
  }
  reader.readAsArrayBuffer(file)
}

async function onConfirm() {
  try {
    await axios.post('/api/question/adds', questions.value)
    previewDialog.value = false
    ElMessage.success('批量添加成功')
    questions.value = []
    fileName.value = ''
  } catch (err) {
    console.error(err)
    ElMessage.error('上传失败，请重试')
  }
}

function onCancel() {
  previewDialog.value = false
}
</script>

<style scoped>
/* Tailwind CSS 已覆盖样式，无需额外 scoped CSS */
</style>
